'use strict';

const app = require('../app')
const oauthCli = require('../wechat/oauth')
const wilddogApi = require('../libs/wilddogApi')

app.get('/oauth', function (req, res) {
  var location = req.query.location
  var code = req.query.code
  console.log('code', code)
  oauthCli.getAccessToken(code, function (err, result) {
    console.log(err)
    console.log(result)
    if (!result.data) return res.send('unknown error')
    var openid = result.data.openid
    console.log('openid', openid)
    oauthCli.getUser(openid, function (err, userInfo) {
      console.log('openid2', openid)
      res.cookie('wx_userinfo', userInfo, { maxAge: 60000 })
      console.log(location)
      switch (location) {
        case 'home':
          res.redirect('/')
          break
        case 'signUp':
          var main = req.query.main
          var sub = req.query.sub
          res.redirect(`/#!/tournaments/details?id=${main}&sub=${sub}`)
          break
        case 'viewBracket':
          var main = req.query.main
          var sub = req.query.sub
          res.redirect(`/#!/tournaments/details/orders?id=${main}&sub=${sub}`)
          break
        case 'viewTournament':
          var main = req.query.main
          res.redirect(`/#!/tournaments/details?id=${main}`)
          break
        case 'notification':
          res.redirect(`/#!/notification`)
          break
        case 'doubles':
          res.redirect(`/#!/user/doubles`)
          break
        default:
          res.redirect(`/#!/`)
          break
      }
    })
  })
})


app.get('/match/join', function (req, res) {
  const roomId = req.query.roomid
  const userObjId = req.query.user

  wilddogApi.joinRoom('-KL7-ZeOyw_Unc5JLywx', userObjId)
  .then(ret => {
    var state = ret.state || 'success'
    res.render('match/joinMatch', {
      data: {
        state,
        url: `${host}/!#/newMatch?roomId=${roomId}`
      }
    })
  }).catch(err => {
    res.render('match/joinMatch', {
      data: {
        state: err
      }
    })
  })
})
